package cn.spark.study.streaming;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

/**
 * 数据库连接池
 *
 * @author zhangj
 * @date 2020/11/19
 */
public class ConnectionPool {

	/**
	 * 加载驱动
	 */
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 静态的队列
	 */
	private static LinkedList<Connection> connectionQueue;

	public synchronized static Connection getConnection() {
		try {
			if (connectionQueue == null) {
				connectionQueue = new LinkedList<Connection>();
				for (int i = 0; i < 10; i++) {
					Connection conn = DriverManager.getConnection(
							"jdbc:mysql://spark1:3306/testdb",
							"",
							"");
					connectionQueue.push(conn);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connectionQueue.poll();
	}

	/**
	 * 还回去一个连接
	 */
	public static void returnConnection(Connection conn) {
		connectionQueue.push(conn);
	}
}
